package us.kg.kotoriforest.schedule.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 工具类。重写 service 方法，通过反射的方式调用类内处理不同业务请求的方法。
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/12/3
 */
public abstract class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 根据请求的 uri 明确要调用的方法名
        String[] split = req.getRequestURI().split("/");
        String methodName = split[split.length - 1];

        // 通过反射来调用相应的方法
        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
